package com.cuitrip.business.home.travel;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;

import com.cuitrip.apiservice.ServiceBusiness;
import com.cuitrip.apiservice.model.ApiManager;
import com.cuitrip.app.MainApplication;
import com.cuitrip.service.R;
import com.cuitrip.util.FlowLayout;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragment;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.utils.LogHelper;
import com.lab.utils.MessageUtils;
import com.lab.utils.Utils;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.Bind;


/**
 * Created by sheena on 15/11/4.
 */
public class TravelTripFeatureShowFragment extends CustomUiFragment implements IProxyCallback{
    private static final String TAG = "TripEditActivity";

    @Bind(R.id.tags_layout)
    protected ScrollView mTagLayout;
    @Bind(R.id.progress_bar)
    protected ProgressBar mLoadingProgress;

    @Bind(R.id.tags_limit_num)
    TextView tagsLimitNum;

    public static final String TAG_KEY = "trip_tag_key";

    private List<String> tags = new ArrayList<>();
    public  List<String> selectedTags = new ArrayList<>();
    private boolean isFetchingTags = false;
    private String[] tagsOutPut;
    public static final int MAX_TAG_SIZE = 4;
    private View view;
    private  String[] featureArray;

    private ApiProxy mApiProxy = new ApiProxy(this);



    public TravelTripFeatureShowFragment() {
    }
    public static TravelTripFeatureShowFragment newInstance(String[] featureArray){
        TravelTripFeatureShowFragment featureShowFragment=new TravelTripFeatureShowFragment();
        Bundle budle=new Bundle();
        budle.putStringArray("tags",featureArray);
        featureShowFragment.setArguments(budle);
        return featureShowFragment;
    }

    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig customUiConfig = new CustomUiConfig();
        customUiConfig.mTopbarMiddleAreaName = getString(R.string.filter_option_featured);
        customUiConfig.mTopbarLeftAreaName = getString(R.string.back_icon);
        return customUiConfig;
    }

    //回退键
    @Override
    public void onTopbarLeftPress() {
        if(TextUtils.isEmpty(retriveTagsText())){
            mDataSendBackListenr.dataSendBack(getString(R.string.value_no_limit));
        }else {
            mDataSendBackListenr.dataSendBack(retriveTagsText());
        }

        getHostActivity().onBackPressed();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view=super.onCreateView(inflater, container, savedInstanceState,R.layout.fragment_select_feature);
        ButterKnife.bind(this, view);

        this.featureArray=getArguments().getStringArray("tags");
        tagsOutPut = featureArray;
        revertTags();
        tryFetchTags();

        return view;
    }

    @Override
    public void initView() {
        //设置标签最多可选几个
        tagsLimitNum.setText(String.format(getResources().getString(R.string.trip_attribute_tag_limit),4));
    }

    public void tryFetchTags() {
        if (tags.isEmpty() && !isFetchingTags) {
            fetchTags();
        }
    }
    public  void  revertTags(){
        if(tagsOutPut!=null){
            selectedTags=new ArrayList<>();
            for(String tag:tagsOutPut){
                selectedTags.add(tag);
            }
        }
        tempTags.clear();
        tempTags.addAll(selectedTags);
    }


    public void fetchTags() {
        isFetchingTags = true;
        ServiceBusiness.getServiceTags(mApiProxy);
    }

    private void inflateTags() {
        mLoadingProgress.setVisibility(View.GONE);
        mTagLayout.setVisibility(View.VISIBLE);
        buildViews();
    }

    public int widthSize = 3;
    private int buttonHeight = Utils.dp2pixel(30);
    public List<String> tempTags = new ArrayList<>();
    /*private TextView initTagItem(final String tag, LinearLayout.LayoutParams innerParams) {
        TextView textView = new TextView(getHostActivity());
        textView.setGravity(Gravity.CENTER);
        textView.setLayoutParams(innerParams);
        textView.setText(tag);
        textView.setTag(tag);
        textView.setHeight(Utils.dp2pixel(30));
        textView.setBackgroundResource(R.drawable.select_alpha_orange_corner);
        textView.setTextColor(getResources().getColorStateList(R.color.ct_white_qiaomai));
        textView.setOnClickListener(onClickListener);
        return textView;
    }*/
    private TextView initTagItem(final String tag){
        TextView textView = new TextView(getHostActivity());
        textView.setGravity(Gravity.CENTER);
        textView.setText(tag);
        textView.setTag(tag);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
        int padding1=Utils.dp2pixel(16);
        int padding2=Utils.dp2pixel(8);
        textView.setPadding(padding1, padding2, padding1, padding2);
        //textView.setLayoutParams();
        textView.setBackgroundResource(R.drawable.select_alpha_orange_corner);
        textView.setTextColor(getResources().getColorStateList(R.color.ct_white_qiaomai));
        textView.setOnClickListener(onClickListener);
        return textView;
    }
    private void buildViews() {
        mTagLayout.clearFocus();

       /* LinearLayout wrapper = null;
        for (int i = 0; i < tags.size(); i++) {
            String tag = String.valueOf(tags.get(i));
            if (i % widthSize == 0) {
                if (wrapper != null) {
                    mTagLayout.addView(wrapper);
                }
                wrapper = initLineWrapper();
            }

            TextView categoryItem = initTagItem(String.valueOf(tags.get(i)), initInnerTagWidth());
            wrapper.addView(categoryItem);
            if (i == tags.size() - 1) {
                if (wrapper != null) {
                    mTagLayout.addView(wrapper);
                }
            }
            categoryItem.setSelected(tempTags.contains(tag));
        }*/
        FlowLayout flowLayout=new FlowLayout(getHostActivity());
        for (int i = 0; i < tags.size(); i++) {
            String tag = String.valueOf(tags.get(i));
            TextView categoryItem = initTagItem(String.valueOf(tags.get(i)));
            flowLayout.addView(categoryItem);
            categoryItem.setSelected(tempTags.contains(tag));
        }
        mTagLayout.addView(flowLayout);

    }

    protected void saveTags() {
        selectedTags = tempTags;
    }

    protected String retriveTagsText() {
        saveTags();
        return TextUtils.join("/",selectedTags);
    }

    private LinearLayout initLineWrapper() {
        LinearLayout layout = new LinearLayout(getHostActivity());
        layout.setOrientation(LinearLayout.HORIZONTAL);

        LinearLayout.LayoutParams params =
                new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
        int margin = Utils.dp2pixel(5);
        params.setMargins(margin, Utils.dp2pixel(8), margin, margin);

        layout.setLayoutParams(params);

        // 第一行的时候需要加点空间
        return layout;
    }

    protected View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String tag = (String) v.getTag();
            if(v.isSelected()){
                LogHelper.e("omg", "deselect " + tag);
                tempTags.remove(tag);
                v.setSelected(false);
            }else {
                if (tempTags.size() >= MAX_TAG_SIZE) {
                    MessageUtils.showToast(getString(R.string.trip_attribute_tag_limit, 4));
                    return;
                }
                LogHelper.e("omg", "select " + tag);
                v.setSelected(true);
                tempTags.add(tag);
            }
        }
    };

    private LinearLayout.LayoutParams initInnerTagWidth() {
        int pageWidth = MainApplication.getInstance().getPageWidth();
        int outSideMargin = Utils.dp2pixel(5);
        int innerMargin = Utils.dp2pixel(5);
        int tagMargin = outSideMargin + innerMargin;
        int tagPerMargin = innerMargin + innerMargin;
        int tagWidth = (pageWidth - 2 * tagMargin - 2 * tagPerMargin) / 3;

        LinearLayout.LayoutParams innerParams = new LinearLayout.LayoutParams(tagWidth, buttonHeight);
        int m = Utils.dp2pixel(4);
        innerParams.setMargins(m, 0, m, 0);
        return innerParams;
    }





    public void onCreateOptionsMenu(Menu menu,MenuInflater inflater) {
        getHostActivity().getMenuInflater().inflate(R.menu.ct_menu_save, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    private void saveAction(){
        saveTags();
        Intent intent = new Intent();
        intent.putExtra(TAG_KEY, retriveTagsText());
        getHostActivity().setResult(getHostActivity().RESULT_OK, intent);
        getHostActivity().finish();
    }


    @Override
    public boolean onBackPressed() {
        saveAction();
        return super.onBackPressed();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public boolean onProxyResult(ProxyResult<?> result) {
        CtApiResponse response = (CtApiResponse) result.getData();
        if (ApiManager.GET_SERVICE_TAG.equals(response.getApiName())){
            if (response != null && response.isResponseNormal()){
                if (response.result instanceof List){
                    try {
                        List<String> datas = (List<String>)response.result;
                        tags = datas;
                    } catch (Exception e) {
                        LogHelper.e("get tags", "error" + e.getMessage());
                    }
                    isFetchingTags = false;
                    inflateTags();
                }
            }else{
                isFetchingTags = false;
            }
        }
        return false;
    }

    public interface DataSendBackListener{
        public void dataSendBack(String data);
    }

    private DataSendBackListener mDataSendBackListenr;

    public void setResultListener(DataSendBackListener listener){
        mDataSendBackListenr=listener;
    }


}
